<?php

declare(strict_types=1);

namespace App\Service;

/**
 * 动态审核服务
 * Class MomentsApplyService
 * @package App\Service
 */
class MomentsApplyService extends BaseService
{

    const STATUS_DRAFT = 0;// 草稿

    const STATUS_WAIT_CHECK = 1; // 待审核

    const STATUS_CHECKED = 2;// 已审核

    const STATUS_REFUSED = 3;// 已驳回

    /**
     * 获取审核内容
     * @param array $data
     * @return array
     */
    public function getApplyData(array $data): array
    {
        $data = [
            'shop_id' => $data['shop_id'],
            'user_id' => $data['user_id'],
            'type' => $data['type'],
            'apply_time' => time(),
            'apply_status' => $data['act'],
            'video_file' => $data['video_file'] ?? 0,
            'video_url' => $data['video_url'] ?? "",
            'video_desc' => $data['video_desc'] ?? "",
            'article' => $data['article'] ?? "",
            'article_title' => $data['article_title'] ?? "",
            'product_json' => $data['product_json'],
            'files_json' => $data['files_json'],
            'topic_id' => $data['topic_id'] ?? 0,
            'moments_style' => $data['moments_style'] ?? 1
        ];
        return $data;
    }

    /**
     * 保存申请变更单
     * @param array $data
     * @return int apply_id
     */
    public function saveApply(array $data): int
    {
        $filter_data = array_filter($data, function ($fields) {
            if (!in_array($fields, ['moments_id', 'shop_id', 'user_id', 'moments_style', 'topic_id', 'type', 'apply_time', 'apply_status', 'video_file', 'video_desc', 'article', 'article_title', 'product_json', 'files_json'])) {
                return false;
            } else {
                return true;
            }
        }, ARRAY_FILTER_USE_KEY);
        // 草稿状态下的可进行编辑（否则为新申请操作）
        $instance = $this->getModelInstance()
            ->where('user_id', '=', $filter_data['user_id'])
            ->where('moments_id', '=', $filter_data['moments_id'])
            ->where('apply_status', '=', self::STATUS_DRAFT)
            ->where('moments_style', '=', $filter_data['moments_style'] ?? 1)
            ->first();

        if (empty($instance) || empty($instance->toArray())) {
            // 完善信息并提交审核
            $instance = $this->getModelInstance();
        }

        // 删除之前待审核申请单，以当前最新为准
        $this->getModelInstance()
            ->where([
                'user_id' => $filter_data['user_id'],
                'apply_status' => 1,
                'moments_style' => $filter_data['moments_style'] ?? 1,
                'moments_id' => $filter_data['moments_id'],
                'delete_time' => 0])
            ->update(['delete_time' => time()]);

        foreach ($filter_data as $field => $val) {
            $instance->$field = $val;
        }
        if (!$instance->save()) {
            return 0;
        }
        return $instance->id;
    }

    /**
     * 删除申请
     * @param int $moments_id
     * @return bool
     */
    public function deleteApply(int $moments_id): bool
    {
        return (bool)$this->getModelInstance()
            ->where(['moments_id' => $moments_id])
            ->whereIn('apply_status', [self::STATUS_WAIT_CHECK, self::STATUS_DRAFT])
            ->update(['delete_time' => time()]);
    }

    /**
     * 取消上架:(0620:取消并编辑，不点击编辑原来状态不变)
     * @param int $moments_id
     * @return bool
     */
    public function downAndModify(int $moments_id): bool
    {
        // 已提交审核的撤回
        $instance = $this->getModelInstance()->where('moments_id', '=', $moments_id)
            ->where('apply_status', '=', self::STATUS_WAIT_CHECK)
            ->first();
        if (empty($instance)) {
            return false;
        }
        $instance->apply_status = self::STATUS_DRAFT;// 取消待审核的申请
        if (!$instance->save()) {
            return false;
        }
        return true;
    }

    /**
     * 动态审核详情
     * @param int $user_id
     * @param int $applys_id
     * @return array
     */
    public function getApplyInfos(int $user_id, int $applys_id): array
    {
        $apply_data = $this->getModelInstance()
            ->where(['user_id' => $user_id, 'id' => $applys_id])
            ->orderBy('apply_time', 'desc')
            ->with(['with_moments_info', 'with_topic_info'])
            ->whereHas('with_moments_info', function ($where) {
                return $where->where('delete_time', '=', 0);
            })
            ->first();
        if (empty($apply_data)) {
            return [];
        }
        $return = $apply_data->toArray();
        $return['files_json_arr'] = empty($return['files_json']) ? [] : json_decode($return['files_json'], true);
        $return['product_json_arr'] = empty($return['product_json']) ? [] : json_decode($return['product_json'], true);
        $return['apply_time'] = empty($return['apply_time']) ? "" : date("Y-m-d H:i:s", $return['apply_time']);
        $return['check_time'] = empty($return['check_time']) ? "" : date("Y-m-d H:i:s", $return['check_time']);
        if (!empty($return['with_moments_info'])) {
            $return['with_moments_info']['create_time'] = empty($return['with_moments_info']['create_time']) ? "" : date("Y-m-d H:i:s", $return['with_moments_info']['create_time']);;
            $return['with_moments_info']['update_time'] = empty($return['with_moments_info']['update_time']) ? "" : date("Y-m-d H:i:s", $return['with_moments_info']['update_time']);
        }

        if (!empty($return['product_json_arr'])) {
            foreach ($return['product_json_arr'] as &$item) {
                $item['price'] = floatval($item['price']);
            }
        }
        return $return;
    }

    /**
     * 根据动态ID获取最新的申请信息
     * @param int $moments_id
     * @return array
     */
    public function getApplyByMomentsID(int $moments_id): array
    {
        $applyInfo = $this->getModelInstance()
            ->where(['moments_id' => $moments_id])
            ->orderBy('id', 'desc')
            ->first();
        return empty($applyInfo) ? [] : $applyInfo->toArray();
    }
}